package com.mmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import com.mmall.common.RequestHolder;
import com.mmall.dao.SysRoleUserMapper;
import com.mmall.dao.SysUserMapper;
import com.mmall.exception.ParamException;
import com.mmall.param.UserParm;
import com.mmall.pojo.SysUser;
import com.mmall.service.ISysLogService;
import com.mmall.service.ISysUserService;
import com.mmall.util.BeanValidatorUtil;
import com.mmall.util.IpUtil;
import com.mmall.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Author wangtengyu
 * @Create 2018-03-10-9:45
 */
@Service("iSysUserService")
public class SysUserServiceImpl implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private ISysLogService iSysLogService;

    public void save(UserParm userParm){
        BeanValidatorUtil.check(userParm);
        if(checkTelphoneExists(userParm.getTelephone(),userParm.getId())){
            throw new ParamException("电话已被占用");
        }
        if(checkEmailExists(userParm.getMail(),userParm.getId())){
            throw new ParamException("邮箱已被占用");
        }
        //一种是通过passwordUtil随机生成密码 发送到邮箱
        //一种是让用户自己填写密码
        String password="123456";
        String md5Password=MD5Util.MD5Encode(password,"utf-8");
        SysUser user=SysUser.builder().username(userParm.getUsername()).telephone(userParm.getTelephone()).mail(userParm.getMail())
                .password(md5Password).deptId(userParm.getDeptId()).status(userParm.getStatus()).remark(userParm.getRemark()).build();
        user.setOperator(RequestHolder.getCurrentUser().getUsername());
        user.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        user.setOperateTime(new Date());
        
        //// TODO: 2018/3/10 发送邮件

        sysUserMapper.insertSelective(user);
        iSysLogService.saveUserLog(null,user);

    }

    public void update(UserParm userParm){
        BeanValidatorUtil.check(userParm);
        if(checkTelphoneExists(userParm.getTelephone(),userParm.getId())){
            throw new ParamException("电话已被占用");
        }
        if(checkEmailExists(userParm.getMail(),userParm.getId())){
            throw new ParamException("邮箱已被占用");
        }
        SysUser before=sysUserMapper.selectByPrimaryKey(userParm.getId());
        Preconditions.checkNotNull(before,"待更新的用户不存在");
        SysUser after=SysUser.builder().id(userParm.getId()).username(userParm.getUsername()).telephone(userParm.getTelephone()).mail(userParm.getMail())
                .deptId(userParm.getDeptId()).status(userParm.getStatus()).remark(userParm.getRemark()).build();
        after.setOperator("system");
        after.setOperateIp("127.0.0.1");
        after.setOperateTime(new Date());
        sysUserMapper.updateByPrimaryKeySelective(after);
        iSysLogService.saveUserLog(before,after);

    }

    /**
     * 校验登录方式 邮箱或者电话
     * @param keyword
     * @return
     */
    public SysUser findBykeyword(String keyword){
        return sysUserMapper.findByKeyword(keyword);
    }


    /**
     * 获取用户列表
     * @param deptId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<SysUser> getUserList(int deptId, int pageNum, int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> sysUserList=sysUserMapper.getUserList(deptId);
        PageInfo<SysUser> pageInfo=new PageInfo<SysUser>(sysUserList);
        return pageInfo;
    }

    /**
     * 获得所有用户
     * @return
     */
    public List<SysUser> getAll(){
        return sysUserMapper.getAll();
    }

    /**
     * 删除用户
     * @param userId
     */
    @Transactional
    public void delete(int userId){
        SysUser user= sysUserMapper.selectByPrimaryKey(userId);
        Preconditions.checkNotNull(user,"待删除的用户不存在");
        sysUserMapper.deleteByPrimaryKey(user.getId());
        sysRoleUserMapper.deleteByUserId(userId);
        iSysLogService.saveUserLog(user,null);

    }



    //检查是否存在，不同部门下可以重名
    //邮箱重复校验
    public boolean checkEmailExists(String mail, Integer userId){
        return sysUserMapper.countByEmail(mail,userId)>0;
    }

    //电话重复校验
    public boolean checkTelphoneExists(String telphone,Integer userId){
        return sysUserMapper.countByTelphone(telphone,userId)>0;
    }
}
